package com.baseproject.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.support.v7.widget.AppCompatImageView;
import android.util.AttributeSet;

import com.baseproject.R;


public class RatioImageView extends AppCompatImageView {
    //高宽比，由我们自己设定
    private float mRatio;
    /**
     * 需要Ratio的是宽度还是高度
     */
    private String mNeedSize;

    public RatioImageView(Context context, float ratio) {
        super(context);
        mRatio = ratio;
    }

    public RatioImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RatioImageView);
        //根据属性名称获取对应的值，属性名称的格式为类名_属性名
        mRatio = typedArray.getFloat(R.styleable.RatioImageView_ratio, 0.0f);
        mNeedSize = typedArray.getString(R.styleable.RatioImageView_needSize);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        //获取宽度的模式和尺寸
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        //获取高度的模式和尺寸
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        //宽确定，高不确定
        if ("height".equals(mNeedSize) && mRatio != 0) {
            heightSize = (int) (widthSize * mRatio + 0.5f);//根据宽度和比例计算高度
            heightMeasureSpec = MeasureSpec.makeMeasureSpec(heightSize, MeasureSpec.EXACTLY);
        } else if ("width".equals(mNeedSize) && mRatio != 0) {
            widthSize = (int) (heightSize / mRatio + 0.5f);
            widthMeasureSpec = MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY);
        } else {
            throw new RuntimeException("无法设定宽高比");
        }
        //必须调用下面的两个方法之一完成onMeasure方法的重写，否则会报错
//        super.onMeasure(widthMeasureSpec,heightMeasureSpec);
        setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
    }

    /**
     * 设置宽高比
     *
     * @param ratio
     */
    public void setRatio(float ratio) {
        this.mRatio = ratio;
    }
}
